package com.szxy.miaosha.service.impl;

import com.szxy.miaosha.dao.GoodsMapper;
import com.szxy.miaosha.service.GoodsService;
import com.szxy.miaosha.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.util.List;

/**
 * @Author: zwz
 * @Date:2020/9/8 21:24
 * @Description:com.szxy.miaosha.service.impl
 * @Version:1.0
 **/
@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public void reduceStock(long goodsId) {
        goodsMapper.updateMiaoGoodsStockByGoodsId(goodsId);
    }

    @Override
    public GoodsVo getGoodsByGoodsId(long goodsId) {
        return goodsMapper.getGoodsByGoodsId(goodsId);
    }

    @Override
    public void showDetail(Model model, Long goodsId) {
        GoodsVo goodsVo = getGoodsByGoodsId(goodsId);
        long statTime = goodsVo.getStartDate().getTime();
        long endTime = goodsVo.getEndDate().getTime();

        // 获取当前时间
        long now = System.currentTimeMillis();
        // 0 秒杀未开始
        // 1 秒杀进行中
        // 2 秒杀结束
        int miaoshaStatus = 0;
        int remainSeconds = 0;
        if (now - statTime < 0) {
            miaoshaStatus = 0;
            remainSeconds = (int) ((statTime - now) / 1000);
        } else if (now - statTime > 0 && now - endTime < 0) {
            miaoshaStatus = 1;
            remainSeconds = 0;
        } else {
            miaoshaStatus = 2;
            remainSeconds = -1;
        }
        log.info("miaoShaStaus: " + miaoshaStatus);
        model.addAttribute("goods", goodsVo);
        model.addAttribute("miaoshaStatus", miaoshaStatus);
        model.addAttribute("remainSeconds", remainSeconds);
    }

    @Override
    public List<GoodsVo> listGoods() {
        return goodsMapper.listGoods();
    }
}
